package com.example.controller;

import com.example.common.response.Result;
import com.example.model.entity.Post;
import com.example.service.FileService;
import com.example.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/content")
public class ContentController {
    @Autowired
    private FileService fileService;
    
    @Autowired
    private PostService postService;

    @GetMapping("/list")
    public Result<Page<Post>> getContentList(
            @RequestParam(required = false) String category,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        // 页码从0开始
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Page<Post> posts = postService.findByCategory(category, pageRequest);
        return Result.success(posts);
    }

    @PostMapping("/upload/avatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file) {
        String filePath = fileService.uploadFile(file, "avatars");
        return Result.success(filePath);
    }

    @PostMapping("/upload/post")
    public Result<String> uploadPostImage(@RequestParam("file") MultipartFile file) {
        String filePath = fileService.uploadFile(file, "posts");
        return Result.success(filePath);
    }
}